package com.gsoc.spreadsheet.client;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class DataCell<T> extends Widget implements RPCIntAsync {

	private T data;
	private int x, y;
	private TextBox text = new TextBox();
	private RPCIntAsync service = (RPCIntAsync) GWT.create(RPCInt.class);
	private ServiceDefTarget endpoint = (ServiceDefTarget) service;

	
	public DataCell(int newX, int newY) {
		x = newX;
		y = newY;
		endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "rpc");
		
		text.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				Window.alert("You clicked cell (" + x + ", " + y + ")!");
			}
		});
	}
	
	public DataCell(T input, int newX, int newY) {
		data = input;
		x = newX;
		y = newY;
		endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "rpc");
		getServerData(x, y, new AsyncCallback() {
			public void onSuccess(Object result) {
				data = (T)result;
			}
			
			public void onFailure(Throwable caught) {
				return;
			}
		});
		
		text.setText(data.toString());
		text.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				Window.alert("You clicked cell (" + x + ", " + y + ")!");
			}
		});

	}
	
	public T getData() { return data; }
	public int getX() { return x; }
	public int getY() {	return y; }
	
	public void setData(T input) {
		data = input;
	}
	
	public void setX(int newX) {
		x = newX;
	}
	
	public void setY(int newY) {
		y = newY;
	}
	
	public void getServerData(int x, int y, AsyncCallback callback) {
		service.getServerData(x, y, callback);
	}
	
	public boolean equals(DataCell<T> other) {
		if(other.getData().equals(data))
			return true;
		else return false;
	}
	
	public TextBox view() {
		return text;
	}
	
	public void myString(String s, AsyncCallback callback) {
		service.myString(s, callback);
	}

}